//
//  AppDelegate.m
//  SinceLe
//
//  Created by 李元喜 on 15/11/11.
//  Copyright © 2015年 李元喜. All rights reserved.
//

#import "AppDelegate.h"
#import <MJRefresh.h>
#import <MBProgressHUD.h>
#import <UIImageView+WebCache.h>
#import <RESideMenu.h>
#import <AVOSCloud.h>
#import "LeftViewController.h"
#import "MusicViewController.h"
#import "MovieViewController.h"
#import "ChatViewController.h"
#import "UserManagerViewController.h"
#import "MyTabBar.h"
#import "MyNavigationController.h"
#import "CDAppDelegate.h"
#import "CDCommon.h"
#import "CDLoginVC.h"
#import "CDBaseTabC.h"
#import "CDBaseNavC.h"
#import "CDConvsVC.h"
#import "CDFriendListVC.h"
#import "CDProfileVC.h"
#import "CDAbuseReport.h"
#import "CDCacheManager.h"

#import "CDUtils.h"
#import "CDAddRequest.h"
#import "CDIMService.h"
#import "LZPushManager.h"
#import <iRate/iRate.h>
#import <iVersion/iVersion.h>
#import <LeanCloudSocial/AVOSCloudSNS.h>
#import <OpenShare/OpenShareHeader.h>


@interface AppDelegate ()

@property (nonatomic, strong) CDLoginVC *loginVC;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//    [self setUI];
//    [self setLeaCloud];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    [CDAddRequest registerSubclass];
    [CDAbuseReport registerSubclass];
#if USE_US
    [AVOSCloud useAVCloudUS];
#endif
    [AVOSCloud setApplicationId:AVOSAppID clientKey:AVOSAppKey];
    //    [AVOSCloud setApplicationId:CloudAppId clientKey:CloudAppKey];
    //    [AVOSCloud setApplicationId:PublicAppId clientKey:PublicAppKey];
    
    [AVOSCloud setLastModifyEnabled:YES];
    
    if (SYSTEM_VERSION >= 7.0) {
        [[UINavigationBar appearance] setBarTintColor:NAVIGATION_COLOR];
        [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    }
    else {
        [[UINavigationBar appearance] setTintColor:NAVIGATION_COLOR];
    }
    [[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                          [UIColor whiteColor], NSForegroundColorAttributeName, [UIFont boldSystemFontOfSize:17], NSFontAttributeName, nil]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    if ([AVUser currentUser]) {
        // Applications are expected to have a root view controller at the end of application launch
        self.window.rootViewController = [[UIViewController alloc] init];
        [self toMain];
    }
    else {
        [self toLogin];
    }
    
    [[LZPushManager manager] registerForRemoteNotification];
    
    [AVAnalytics trackAppOpenedWithLaunchOptions:launchOptions];
    [self initAnalytics];
    
#ifdef DEBUG
    [AVPush setProductionMode:NO];  // 如果要测试申请好友是否有推送，请设置为 YES
    [AVOSCloud setAllLogsEnabled:YES];
#endif
    return YES;
}

- (void)initAnalytics {
    [AVAnalytics setAnalyticsEnabled:YES];
#ifdef DEBUG
    [AVAnalytics setChannel:@"Debug"];
#else
    [AVAnalytics setChannel:@"App Store"];
#endif
    // 应用每次启动都会去获取在线参数，这里同步获取即可。可能是上一次启动获取得到的在线参数。不过没关系。
    NSDictionary *configParams = [AVAnalytics getConfigParams];
    DLog(@"configParams: %@", configParams);
}

-(void)setLeaCloud{
    [AVOSCloud setApplicationId:@"wyJCfAGOizlcHeX7JLUEKnja" clientKey:@"qlYRjhIV2bCRqI6iSCuO6MgU"];
}

//-(void)setUI{
//    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
//    self.window.backgroundColor = [UIColor whiteColor];
//    
//    //抽屉左边的效果
//    LeftViewController* leftVC = [[LeftViewController alloc] init];
//    
//    MusicViewController* musicVC =[[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"music"];//音乐
//    
//    
//    
//    
//    MovieViewController* movieVC = [[MovieViewController alloc] init];
//    ChatViewController* chatVC = [[ChatViewController alloc] init];
//    UserManagerViewController* userVC = [[UserManagerViewController alloc] init];
//    
//    
//    musicVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"音乐" image:nil tag:101];
//    movieVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"电影" image:nil tag:102];
//    chatVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"聊天" image:nil tag:103];
//    userVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"用户" image:nil tag:104];
//    musicVC.title = @"音乐库";
//    movieVC.title = @"电影";
//    chatVC.title = @"聊天";
//    userVC.title = @"用户";
//    
//    MyNavigationController* musicNV = [[MyNavigationController alloc] initWithRootViewController:musicVC];
//    MyNavigationController* movieNV = [[MyNavigationController alloc] initWithRootViewController:movieVC];
//    MyNavigationController* chatNV = [[MyNavigationController alloc] initWithRootViewController:chatVC];
//    MyNavigationController* userNV = [[MyNavigationController alloc] initWithRootViewController:userVC];
//
//    
//    MyTabBar* tabBar = [[MyTabBar alloc] init];
//    tabBar.viewControllers = @[movieNV, musicNV, chatNV, userNV];
//    
//    RESideMenu* drawer = [[RESideMenu alloc] initWithContentViewController:tabBar leftMenuViewController:leftVC rightMenuViewController:nil];
//    drawer.backgroundImage = [UIImage imageNamed:@"Stars"];
//    
//    self.window.rootViewController = drawer;
//    
//    [[UINavigationBar appearance] setTranslucent:NO];
//    
//    [self.window makeKeyAndVisible];
//    
//}

- (MusicViewController *)addMusicVC
{
    return  [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"music"];//音乐
}


- (void)applicationWillResignActive:(UIApplication *)application {
    [[LZPushManager manager] syncBadge];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [application cancelAllLocalNotifications];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    [[LZPushManager manager] syncBadge];
}

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [[LZPushManager manager] saveInstallationWithDeviceToken:deviceToken userId:[AVUser currentUser].objectId];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    DLog(@"%@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    if (application.applicationState == UIApplicationStateActive) {
        // 应用在前台时收到推送，只能来自于普通的推送，而非离线消息推送
    }
    else {
        //  当使用 https://github.com/leancloud/leanchat-cloudcode 云代码更改推送内容的时候
        //        {
        //            aps =     {
        //                alert = "lzwios : sdfsdf";
        //                badge = 4;
        //                sound = default;
        //            };
        //            convid = 55bae86300b0efdcbe3e742e;
        //        }
        [[CDChatManager manager] didReceiveRemoteNotification:userInfo];
        [AVAnalytics trackAppOpenedWithRemoteNotificationPayload:userInfo];
    }
    DLog(@"receiveRemoteNotification");
}

- (void)toLogin {
    self.loginVC = [[CDLoginVC alloc] init];
    self.window.rootViewController = self.loginVC;
}

- (void)addItemController:(UIViewController *)itemController toTabBarController:(CDBaseTabC *)tab {
    CDBaseNavC *nav = [[CDBaseNavC alloc] initWithRootViewController:itemController];
    [tab addChildViewController:nav];
}

- (void)toMain{
    [iRate sharedInstance].applicationBundleID = @"com.avoscloud.leanchat";
    [iRate sharedInstance].onlyPromptIfLatestVersion = NO;
    [iRate sharedInstance].previewMode = NO;
    [iVersion sharedInstance].applicationBundleID = @"com.avoscloud.leanchat";
    [iVersion sharedInstance].previewMode = NO;
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    [[CDCacheManager manager] registerUsers:@[[AVUser currentUser]]];
    WEAKSELF
    [CDChatManager manager].userDelegate = [CDIMService service];
    
#ifdef DEBUG
#warning 使用开发证书来推送，方便调试，具体可看这个变量的定义处
    [CDChatManager manager].useDevPushCerticate = YES;
#endif
    
    [[CDChatManager manager] openWithClientId:[AVUser currentUser].objectId callback: ^(BOOL succeeded, NSError *error) {
        DLog(@"%@", error);
        CDBaseTabC *tab = [[CDBaseTabC alloc] init];
        
        MusicViewController* musicVC =[[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"music"];//音乐
        musicVC.title = @"音乐";
        musicVC.tabBarItem.image = [UIImage imageNamed:@"tabbar_music"];


        
        [weakSelf addItemController:[[MovieViewController alloc] init] toTabBarController:tab];
        [weakSelf addItemController:musicVC toTabBarController:tab];
        [weakSelf addItemController:[[CDConvsVC alloc] init] toTabBarController:tab];
        [weakSelf addItemController:[[CDFriendListVC alloc] init] toTabBarController:tab];
        [weakSelf addItemController:[[CDProfileVC alloc] init] toTabBarController:tab];
        
        tab.selectedIndex = 0;
        LeftViewController* leftVC = [[LeftViewController alloc]init];
        RESideMenu* drawer = [[RESideMenu alloc] initWithContentViewController:tab leftMenuViewController:leftVC rightMenuViewController:nil];
        drawer.backgroundImage = [UIImage imageNamed:@"Stars"];
        [[UINavigationBar appearance] setTranslucent:YES];
        weakSelf.window.rootViewController = drawer;
    }];
}

#pragma mark -

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    [AVOSCloudSNS handleOpenURL:url];
    [OpenShare handleOpenURL:url];
    return YES;
}


@end
